package com.wn.consumer.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager;
import com.wn.api.UserApi;
import com.wn.bean.User;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author yellow Docter
 * @date 2023 -08-07
 * @desc
 */
@RestController
@RequestMapping("/user3")
public class User3Controller {

    @Autowired
    private UserApi userApi;

    @ApiOperation("测试Hystrix服务降级3、服务熔断机制")
    @HystrixCommand(fallbackMethod = "errorFallback",
            commandProperties = {
            // 是否开启断路器
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ENABLED,value = "true"),
            // 请求错误率大于 50% 就启动熔断器
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ERROR_THRESHOLD_PERCENTAGE,value = "50"),
            // 默认10秒内访问接口失败达到20次，打开断路器，触发熔断； 为了方便测试，这里修改10秒内错误达到10次触发熔断。
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_REQUEST_VOLUME_THRESHOLD,value = "10"),
            //断路多久以后开始尝试是否恢复，默认5s
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS,value = "10000")
    })
    @GetMapping("get/{id}")
    public User getUserById(@PathVariable("id") Integer id){
        return userApi.findUserById(id);
    }

    //服务降级的方法 （返回一个预先准备好的数据）
    public User errorFallback(@PathVariable("id") Integer id){
        User user = new User();
        user.setName("feign 执行异常.走默认方法....");
        user.setAge(0);
        user.setDesc("aaa");
        return user;
    }
}
